chrome.extension.onRequest.addListener(function(request) {
  	if (request == "render usage info") {
  		renderUsageInfo();
  	}
});

window.notchCount = 0;

function updatePercentageBar() {
	var pb = $("#percentageBar");
	if (window.notchCount < 2) {
		window.notchCount++;
		window.notchLeft = ( ( pb.width() - 2 ) * window.timePercentage ) - ( window.timePercentage < .5 ? 2 : 3 );
	}
	$("#percentageBar img").css("left",window.notchLeft + "px");

	if (unfilledWidth == 0) {
		pb.removeClass("green").addClass("red");
	}
	else if ($("#unfilledPortion").offset().left >= $("#percentageBar img").offset().left+4) {
		pb.removeClass("green").addClass("orange");
	}
}

// Render and display the usage info in the pop-up balloon
function renderUsageInfo() {

	// When pop-up page page is loaded, if data exists in local storage and user has opted to show it, read and display it
	if (localStorage.lastupdate) {
		$("#content table, #links").html("");

		// Data cap
		if (localStorage.popup_dataCap == 1) {
			var dataCap = localStorage.cap == "0" ? "None" : number_format(parseFloat(localStorage.cap) / 1024, 2)+" GB";
			$("#content table").append('<tr class="exact"><td>Data cap:</td><td class="right">'+dataCap+'</td></tr>');
		}

		// Local data used
		if (localStorage.popup_localDataUsed == 1) {
			$("#content table").append('<tr class="exact"><td>Local data used:</td><td class="right">'+number_format((parseFloat(localStorage.rxlocal)+parseFloat(localStorage.txlocal)) / 1024, 2)+" GB</td></tr>");
		}

		// Free data used
		if (localStorage.popup_freeDataUsed == 1) {
			$("#content table").append('<tr class="exact"><td>Free data used:</td><td class="right">'+number_format(parseFloat(localStorage.freedataused) / 1024, 2)+" GB</td></tr>");
		}

		// Standard data used
		if (localStorage.popup_standardDataUsed == 1) {
			$("#content table").append('<tr class="exact"><td>Standard data used:</td><td class="right">'+number_format(parseFloat(localStorage.total) / 1024, 2)+" GB</td></tr>");
		}

		var combinedTotal = parseFloat(localStorage.total) + parseFloat(localStorage.freedataused);
		
		// Total data used
		if (localStorage.popup_dataUsed == 1) {
			var dataUsedText = number_format(combinedTotal / 1024, 2)+" GB";
			var dataUsedDescription = localStorage.popup_localDataUsed == 1 || localStorage.popup_freeDataUsed == 1 || localStorage.popup_standardDataUsed == 1 ? 'Total data used:' : 'Data used:';
			$("#content table").append('<tr class="exact"><td>'+dataUsedDescription+'</td><td class="right">'+dataUsedText+'</td></tr>');
		}
		
		// Data left
		if (localStorage.popup_standardDataLeft == 1) {
			var standardDataLeftText = 'Data remaining:';
			if (localStorage.cap == "0") {
				var standardDataLeft = "N/A";
			} else {
				if (combinedTotal >= parseFloat(localStorage.cap)) {
					var standardDataLeft = "0.00 GB";
				} else {
					var standardDataLeft = number_format((parseFloat(localStorage.cap)-combinedTotal) / 1024, 2)+" GB";
				}
			}
			$("#content table").append('<tr class="exact"><td>'+standardDataLeftText+'</td><td class="right">'+standardDataLeft+'</td></tr>');
		}

		var daysPassed = ( parseFloat(date("U")) - parseFloat(mktime(0,0,0,date("n"),1)) ) / (60 * 60 * 24);
		var avg = combinedTotal / daysPassed;
		avg = number_format(avg / 1024, 2);

		// Daily average
		if (localStorage.popup_dailyAverage == 1) {
			$("#content table").append('<tr class="estimate"><td>Average daily usage:</td><td class="right">'+avg+' GB</td></tr>');
		}

		// Monthly estimate
		if (localStorage.popup_monthlyEstimate == 1) {
			var daysThisMonth = ( parseFloat(mktime(0,0,0,parseFloat(date("n"))+1,1)) - parseFloat(mktime(0,0,0,date("n"),1)) ) / (60 * 60 * 24);
			$("#content table").append('<tr class="estimate"><td>Monthly estimate:</td><td class="right">'+(number_format(daysThisMonth*avg,2))+' GB</td></tr>');
		}
		
		// Target daily average
		if (localStorage.popup_targetDailyAverage == 1) {
			var cap = parseFloat(localStorage.cap);
			if (cap > 0) {
				var dataRemaining = 0;
				var targetDailyUsage = 0;
				if (combinedTotal < cap) {
					dataRemaining = (cap-combinedTotal) / 1024;
					var nextMonth = parseFloat(mktime(0, 0, 0, parseInt(date('n'))+1, 1));
					var daysRemaining = (nextMonth - parseFloat(date('U'))) / (60 * 60 * 24);
					targetDailyUsage = dataRemaining / daysRemaining;
					if (targetDailyUsage > dataRemaining) {
						targetDailyUsage = dataRemaining;
					}
				}
				$("#content table").append('<tr class="estimate"><td>Suggested daily usage:</td><td class="right">'+ number_format(targetDailyUsage, 2) +' GB</td></tr>');
			} else {
				$("#content table").append('<tr class="estimate"><td>Suggested daily usage:</td><td class="right">N/A</td></tr>');
			}
		}

		// Percentage bar
		if (localStorage.popup_percentageBar == 1) {
			var percentage = localStorage.cap == 0 ? 0 : ( combinedTotal / parseFloat(localStorage.cap) ) * 100;
			var percentageText = localStorage.cap == 0 ? "Allowance used: N/A (no data cap)\nNB: a custom cap can be set in the options" : "Allowance used: " + Math.round(percentage) + "%";
			percentage = Math.min(percentage,100);
			window.unfilledWidth = 100-percentage;
			var fullClass = unfilledWidth == 100 ? 'class="full"' : '';

			var nextMonth = parseFloat(mktime(0,0,0,parseFloat(date("n"))+1,1));
			var thisMonth =  parseFloat(mktime(0,0,0,date("n"),1));

			var now = parseFloat(date("U"));
					  // For debug testing:
					  // parseFloat(mktime(23,59,0,date("n"),30));
					  // parseFloat(mktime(0,0,0,date("n"),1));

			window.timePercentage = (now-thisMonth) / (nextMonth-thisMonth);

			$("#content table").append('<tr class="percentageBarSegmentSpacer"><td colspan="2"><div title="'+percentageText+'" id="percentageBar" class="green"><img src="notch.png" /><div id="unfilledPortion" style="width:'+window.unfilledWidth+'%" '+fullClass+'></div></div></td></tr>');

			updatePercentageBar();
		}

		// Cost to date
		if (localStorage.popup_costToDate == 1) {
			$("#content table").append('<tr><td>Cost to date:</td><td class="right">$'+localStorage.bpc+'</td></tr>');
		}

		// Time remaining
		if (localStorage.popup_timeRemaining == 1) {
			var nextMonthTimestamp = parseFloat(mktime(0,0,0, parseFloat(date("n"))+1, 1, date("Y")));
			var nowTimestamp = parseFloat(date("U"));
			var secondsRemaining = nextMonthTimestamp - nowTimestamp;
			var timeRemainingText = '';
			if (secondsRemaining > 60 * 60 * 24) {
				var daysLeft = Math.floor(secondsRemaining / (60 * 60 * 24));
				timeRemainingText = daysLeft + (daysLeft == 1 ? " day" : " days");
			} else {
				var hoursRemaining = Math.floor(secondsRemaining / (60 * 60));
				timeRemainingText = hoursRemaining == 0 ? '&lt; 1 hour' : hoursRemaining + (hoursRemaining == 1 ? ' hour' : ' hours');
			}
			$("#content table").append('<tr><td>Time remaining:</td><td class="right">'+timeRemainingText+'</td></tr>');
		}

		// Time last updated / refresh button
		if (localStorage.popup_timeLastUpdated == 1) {
			var lastUpdated = strtotime(localStorage.lastupdate);
			var dateText = date("j F @ g:i a", lastUpdated);
		    var now = date("U");
		    var minutesPassed = Math.round((now-lastUpdated)/60);
		    if (minutesPassed <= 60) {
		    	if (minutesPassed < 1) {
		    		lastUpdated = "< 1 min ago";
		    	} else if (minutesPassed == 1) {
		    		lastUpdated = " 1 min ago";
		    	} else {
		    		lastUpdated = " "+minutesPassed+" mins ago";
		    	}
		    } else {
				if (date('j M') == date('j M', lastUpdated)) {
					lastUpdated = 'today @ ' + date("g:i a", lastUpdated);
				} else {
					lastUpdated = date("j M @ g:i a", lastUpdated);
				}
		    }
			$("#content table").append('<tr><td colspan="2" id="lastUpdated" style="padding-top:5px; padding-bottom:0;"><img class="reload" src="reload.png" title="Check for updated usage info" style="float:right; padding-left:5px; position:relative; bottom:-1px" /><span style="opacity:.55">Updated <span title="'+dateText+'" style="cursor:help">'+lastUpdated+'</span></span></td></tr>');

			// When user clicks the refresh button, check for new usage info
		    $("img.reload").live("click", function(){
		    	$("#lastUpdated").html('<span style="opacity:.55">Refreshing...</span>');
		    	setTimeout(function(){
		    		chrome.extension.sendRequest("update usage");
		    	}, 1000);
		    });
		}
		
		// Blank space separators
		$('tr.exact').last().addClass('segmentSpacer');
		$('tr.estimate').last().addClass('segmentSpacer');

		// Internal usage history link
		if (localStorage.popup_usageHistory == 1) {
			$("#links").append('<a href="xnet.history.html" target="_blank">Usage History</a><br />');
		}

		// Xnet link
		if (localStorage.popup_xnet == 1) {
			$("#links").append('<a href="http://www.xnet.co.nz/" target="_blank">Xnet.co.nz</a><br />');
		}

		// Network status link
		if (localStorage.popup_networkStatus == 1) {
			$("#links").append('<a href="https://www.xport.co.nz/network-status/" target="_blank">Network Status</a><br />');
		}

		// Speed test link
		if (localStorage.popup_speedTest == 1) {
			$("#links").append('<a href="http://www.xnet.co.nz/support/speed-test/" target="_blank">Speed Test</a><br />');
		}

		// Support link
		if (localStorage.popup_support == 1) {
			$("#links").append('<a href="http://www.xnet.co.nz/support" target="_blank">Support</a><br />');
		}

		// ViewBill link
		/*if (localStorage.popup_viewBill == 1) {
			$("#links").append('<a href="https://viewbill.xport.co.nz/" target="_blank">ViewBill</a><br />');
		}*/
		
		// Xport link
		if (localStorage.popup_xport == 1) {
			$("#links").append('<a href="https://www.xport.co.nz/" target="_blank">Xport (ViewBill)</a><br />');
		}

		// VFX portal link
		if (localStorage.popup_vfxPortal == 1) {
			$("#links").append('<a href="https://myvfx.xport.co.nz/" target="_blank">VFX Portal</a><br />');
		}

		// Webmail link
		if (localStorage.popup_webmail == 1) {
			$("#links").append('<a href="https://webmail.xnet.co.nz/" target="_blank">Webmail</a><br />');
		}

		// Speedtest.net link
		if (localStorage.popup_speedtestDotNet == 1) {
			$("#links").append('<a href="http://speedtest.net/" target="_blank">Speedtest.net</a><br />');
		}

		// Pingtest.net link
		if (localStorage.popup_pingtestDotNet == 1) {
			$("#links").append('<a href="http://pingtest.net/" target="_blank">Pingtest.net</a><br />');
		}

		// XML data file link
		if (localStorage.popup_xmlDataFile == 1) {
			$("#links").append('<a href="https://api.xport.co.nz/usage/?username='+localStorage.username+';token='+localStorage.password+'" target="_blank">XML data file</a><br />');
		}

		// Finish up
		if ($("#links a").length > 0) {
			$("#links").css("display","inline-block").css("margin-top","8px");
		}
		$("#content table").css("width",$("#content table").width()+"px");

	// If local storage data does not exist, inform user that there's an error
	} else {

		// If XML file has been fetched but it contains an error...
		if (localStorage.errstr) {

			// If Xnet reports invalid credentials, close popup and show options page
			if (localStorage.errstr == "Username or Password Incorrect") {
				chrome.tabs.create({url:"xnet.options.html", selected:true});
				window.close();
				return false;
			}

			// Otherwise display the error from Xnet
			$("#content").html('<span style="white-space:nowrap"><b>Unable to retrieve your Xnet usage info.</b><br /><br />Xnet\'s usage server responded:<br />&quot;'+localStorage.errstr+'&quot;</span>');

		// If no XML file is fetched, display a generic message
		} else {
			$("#content").html('<span style="white-space:nowrap"><b>Unable to retrieve your Xnet usage info.</b><br /><br />Xnet\'s usage server might be down, or you might not be connected to the Internet.</span></span>');
		}

		// And add a note that this extension is not officially supported by Xnet
		$("#content").append('<br /><br ><span style="font-size:11px; color:rgba(0,0,0,.55);">Please note: this usage monitor is not officially<br />supported by Xnet.</span>');
	}
}

$(document).ready(function(){
	renderUsageInfo();

	// Show info (slight delay to prevent the pop-up balloon from spazzing out)
	setTimeout(function(){
		$("#content table").first().css("display","");
		$("a").first().css("display","");
		updatePercentageBar();
	}, 20);
});